package com.security.control.core.validate.filter;

import com.security.control.core.properties.SecurityProperties;
import com.security.control.core.support.SecurityConstants;
import com.security.control.core.validate.ValidateCodeProcessorHolder;
import com.security.control.core.validate.exception.ValidateCodeException;
import com.security.control.core.validate.support.ValidateCodeType;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author imoot@gamil.com
 * @date 2018/12/19 0019 10:44
 * ---验证码过滤器
 */
@Component("validateCodeFilter")
public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {

    //验证码校验失败处理器
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    //定义需要拦截的url集合
    private Map<String, ValidateCodeType> urlMap = new HashMap<>();

    //配置信息
    @Autowired
    private SecurityProperties securityProperties;

    //spring的url校验类
    private AntPathMatcher pathMatcher = new AntPathMatcher();

    //校验码处理器的控制器
    @Autowired
    private ValidateCodeProcessorHolder validateCodeProcessorHolder;

    private Logger log = LoggerFactory.getLogger(ValidateCodeFilter.class);

    /**
     * 初始化要拦截的url信息
     * 实现InitializingBean接口并重写afterPropertiesSet()，把配置文件中需要拦截的url保存到Map集合中
     */
    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();

        //把图片验证码的url以及对应的验证码枚举类放入map中
        urlMap.put(SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_FORM, ValidateCodeType.IMAGE);
        addUrlToMap(securityProperties.getImageValidateCodeProperties().getUrl(), ValidateCodeType.IMAGE);

        //把短信验证码的url以及对应的验证码枚举类放入map中
        urlMap.put(SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_MOBILE, ValidateCodeType.SMS);
        addUrlToMap(securityProperties.getSmsValidateCodeProperties().getUrl(), ValidateCodeType.SMS);
    }

    /**
     * @param urlString
     * @param type
     * 把系统中配置的需要校验的url根据校验类型放入map中
     */
    protected void addUrlToMap(String urlString, ValidateCodeType type) {
        if (StringUtils.isNotBlank(urlString)) {
            String[] urls = StringUtils.splitByWholeSeparatorPreserveAllTokens(urlString, ",");
            for (String url : urls) {
                urlMap.put(url, type);
            }
        }
    }

    /**
     * @param request
     * @param response
     * @param filterChain
     * 过滤器执行逻辑
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        ValidateCodeType type = getValidateCodeType(request);
        if (type != null) {
            log.info("校验请求（" + request.getRequestURI() + "）中的验证码，类型为：" + type);
            try {
                validateCodeProcessorHolder.findValidateCodeProcessor(type).validate(new ServletWebRequest((request)));
                log.info("校验通过");
            } catch (ValidateCodeException ex) {
                //如果验证中出现异常或者验证失败，调用自定义登录失败处理类，返回失败（错误）信息
                authenticationFailureHandler.onAuthenticationFailure(request, response, ex);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    /**
     * @param request
     * @return ValidateCodeType
     * 获取校验码类型，如果当前请求不需要校验，则返回null
     */
    private ValidateCodeType getValidateCodeType(HttpServletRequest request) {
        ValidateCodeType result = null;
        if (!StringUtils.equalsIgnoreCase(request.getMethod(), "get")) {
            Set<String> urls = urlMap.keySet();
            for (String url : urls) {
                if (pathMatcher.match(url, request.getRequestURI())) {
                    result = urlMap.get(url);
                }
            }
        }
        return result;
    }
}
